package org.example.springboot.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.example.springboot.entity.*;
import org.example.springboot.service.*;
import org.example.springboot.utils.WeatherApiClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class ETCheckHandler {

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Resource
    private IrrigationUnitService irrigationUnitService;

    @Resource
    private FmcMetricsService fmcMetricsService;

    @Resource
    private ETService etService;

    @Resource
    private FmcControlService fmcControlService;

    @Resource
    private PendingTasksService pendingTasksService;

    @XxlJob("createEtCheckHandler")
    public void createEtCheckHandler() throws IOException {
        String jobParam = XxlJobHelper.getJobParam();
        long jobId = XxlJobHelper.getJobId();
        log.info("createEtCheckHandler-定时任务已执行，任务ID：{}，参数：{}", jobId, jobParam);

        //查询所有灌溉方式是ET灌溉的单元
        List<IrrigationUnit> irrigationUnitList = irrigationUnitService.list(new QueryWrapper<IrrigationUnit>().eq("type", "04"));
        for (IrrigationUnit irrigationUnit : irrigationUnitList) {
            ET et = etService.getOne(new QueryWrapper<ET>().eq("irrigation_unit_uuid", irrigationUnit.getUuid()));
            log.info("ET数据：{}", et);
            //判断对应指标表的ET数据是否大于上限
            String controlDevice = irrigationUnit.getControlDevice();
            FmcMetrics fmcMetrics = fmcMetricsService.getOne(new QueryWrapper<FmcMetrics>().eq("did", controlDevice));
            log.info("fmcMetrics数据：{}", fmcMetrics);
            if (fmcMetrics != null) {
                log.info("ET累加值：{}，上限为：{}", fmcMetrics.getEt(), et.getEvapotranspirationLimit());
                if (fmcMetrics.getEt() >= et.getEvapotranspirationLimit()) {
                    log.info("ET累加值已达到上限，进行灌溉");
                    //如果大于等于上限，判断当日降雨概率是否大于50%
                    String json = WeatherApiClient.sendGetRequest("http://v1.yiketianqi.com/api?unescape=1&version=v63&appid=81191881&appsecret=J6qFGxVz&city=巴彦淖尔");
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    if(jsonObject != null){
                        String wea = jsonObject.get("wea").toString();
                        if (wea.contains("雨")) {
                            return;
                        }
                    }
                    FmcControl fmcControl = new FmcControl();
                    fmcControl.setDid(controlDevice);
                    fmcControl.setUnitCode(irrigationUnit.getUnitCode());
                    fmcControl.setValt(1);
                    fmcControl.setOperationTime(new Date());
                    fmcControl.setTopic("FMC_control/" + controlDevice);
                    JSONObject message = new JSONObject();
                    message.put("project", "ET_Logger");
                    message.put("device", controlDevice);
                    message.put("method", "0");
                    message.put("valt1", "1");
                    //灌溉水量值=灌溉面积*ΣET累加值*修正系数/1000
                    Float area = irrigationUnit.getArea();
                    if (irrigationUnit.getUnit().equals("01")) {
                        area = area * 666.67f;
                    }
                    float v = area * fmcMetrics.getEt() * et.getCoefficient() / 1000;
                    // 保留两位小数并打印
                    String amount = String.format("%.4f", v);
                    message.put("amount", amount);
                    fmcControl.setMessage(message);
                    log.info("开始执行ET灌溉，MQTT消息：{}", message);
                    //如果轮灌组编号是1则直接发送MQTT消息，否则保存至待执行表，等待下一次执行
                    /*if(irrigationUnit.getSym().equals("1")){
                        fmcControlService.sendMessageToMqtt(fmcControl);

                    }*/
                    PendingTasks pendingTasks = new PendingTasks();
                    pendingTasks.setSort(Integer.valueOf(irrigationUnit.getSym()));
                    pendingTasks.setMqttContent(JSONObject.toJSONString(fmcControl));
                    pendingTasksService.save(pendingTasks);
                    et.setIrrigationVolume(Float.valueOf(amount));
                    etService.updateById(et);

                }
            }
        }

        //如果小于则灌溉

        //SSE发送消息成功后销毁定时任务
    /*    XxlJobUtil xxlJobUtil = new XxlJobUtil();
        xxlJobUtil.remove(adminAddresses, Math.toIntExact(jobId));*/
    }

}
